#pragma once
#include <signal.h>
#include<functional>
#include "Socket.hpp"
#include "Protocol.hpp"

using fun_t = std::function<std::string(std::string&package)>;

class Server
{
public:
    Server(uint16_t port,fun_t callback)
        : port_(port),callback_(callback)
    {}
    ~Server()
    {}

public:
    bool InitServer()
    {
        sock_.Socket();
        sock_.Bind(port_);
        sock_.Listen();
        lg(Info, "Init Server ...  done");
        return true;
    }
    void start()
    {
        signal(SIGPIPE, SIG_IGN); // 忽略返回的子进程
        signal(SIGCHLD, SIG_IGN);

        while (true)
        {
            string clientip;
            uint16_t clientport;
            int sockfd = sock_.Accept(&clientip, &clientport);
            if (sockfd < 0)
                continue;
            lg(Info, "accept a new link,sockfd:%d,clientip:%s,clientport:%d", sockfd, clientip, clientport);
            // 提供服务
            if (fork() == 0)
            {
                sock_.Close();
                std::string inbuffer_stream;
                while (true)
                {
                    // 接收客户端的信息
                    char buffer[1280];
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        while(true)
                        {
                            std::string info=callback_(inbuffer_stream);
                            if(info.empty())break;
                            write(sockfd,info.c_str(),info.size());
                        }
                    }
                    else if(n==0)break;
                    else break;
                }
                exit(0);
            }
            close(sockfd);
        }
    }

private:
    fun_t callback_;
    uint16_t port_;
    Sock sock_;
};